package goodroommate.ui.info;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import goodroommate.domain.User;
import goodroommate.exception.DatabaseException;
import goodroommate.service.INewsService;
import goodroommate.service.impl.NewsService;

@WebServlet("/Info/AddInfo")
public class AddInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    INewsService newsService=new NewsService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("addinfo.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("user");
		if(user==null){
			response.sendRedirect(request.getContextPath()+"/Account/Login");
			return;
		}
		
		String subject=request.getParameter("topic");
		String content=request.getParameter("content");
		
		int errorCode=0;
		if(subject==null||"".equals(subject)
				||content==null||"".equals(content)){
			errorCode=1;
			request.setAttribute("errorCode", errorCode);
			request.getRequestDispatcher("addinfo.jsp").forward(request, response);
			return;
		}
		
		try{
			newsService.addNews(subject, content);
			request.setAttribute("errorCode", errorCode);
			request.getRequestDispatcher("addinfo.jsp").forward(request, response);
			return ;	
		}catch(DatabaseException e){
			response.sendError(500);
			return;
		}
	
		
	}

}
